package org.menacheri.jetserver.util;

import game.banana.server.GameConstant;
import game.banana.server.entities.Command;
import game.banana.server.entities.Login;

import java.awt.font.GlyphJustificationInfo;
import java.io.IOException;
import java.io.StringReader;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.google.gson.JsonPrimitive;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonToken;

public class JsonParserWriter {

	public static JsonParserWriter jsonParser = null;
	private Gson gson;
	/***/
	public JsonParserWriter () {
		gson = new GsonBuilder().create();
	}
//	public static JsonParserWriter SharedParser(){
//		if(jsonParser == null) {
//			jsonParser = new JsonParserWriter();
//			jsonParser.init();
//		}
//		return jsonParser;
//	}
//	private void init(){
//		gson = new GsonBuilder().create();
//		
//	}
	
	public synchronized Command parser(String jsonString) {
		JsonElement element = new JsonParser().parse(jsonString);
		JsonObject root =  element.getAsJsonObject();
		
		JsonElement m_service  = root.get("serviceID");
		JsonElement m_command  = root.get("commandID");
		
		int comValue = Integer.parseInt(m_command.toString());
		JsonElement commandData = null;
		Command command = null;
		switch (comValue) {
		case GameConstant.LOGIN:
			commandData  = root.getAsJsonObject("data");
			Login login = gson.fromJson(commandData, Login.class);
			command = new Command(Integer.parseInt(m_service.toString()), Integer.parseInt(m_command.toString()), login);
			break;
		default:
			break;
		}
		return command;
	}
	//convert java object to string 
	public synchronized String Serialization(Command command){
		JsonObject object = new JsonObject();
		object.add("serviceID", new JsonPrimitive(command.getService()));
		object.add("commandID", new JsonPrimitive(command.getCommand()));
		String json  = gson.toJson(command.getData());
		object.add("data", new JsonParser().parse(json).getAsJsonObject());
		return object != null ? object.toString() : null ;
		
	}
	
}

